//
//  NSString+YH.m
//  YHKit
//
//  Created by lin on 2020/6/23.
//  Copyright © 2020 Mac. All rights reserved.
//

#import "NSString+YH.h"
#import <UIKit/UIKit.h>
#import <YYCategories/NSData+YYAdd.h>
#import <YHConstant/YHConstant.h>
#import <YHHUD/YHHUD.h>
#import "NSDate+YH.h"


@implementation NSString (YH)


- (NSString *(^)(NSString * str))yh_append{
    NSString *(^block)(NSString * str) = ^NSString *(NSString * str) {
        
        if(!str || str == nil || [str isEqual:[NSNull class]] || [str isKindOfClass:[NSNull class]]){
            return self;
        }
        if([str isKindOfClass:[NSString class]]){
            return [NSString stringWithFormat:@"%@%@",self,str];
        }
        return [NSString stringWithFormat:@"%@%@",self,str];
    };
    return block;
}


 

/** 转时间日期
 为空默认 yyyy-MM-dd HH:mm:ss 格式
 */
- (NSDate *)yh_dateByFormate:(NSString *)formate{
    NSDateFormatter * dateFormatter = [NSDateFormatter new];
    if(formate){
        dateFormatter.dateFormat = formate;
    }else{
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    }
    return [dateFormatter dateFromString:self];
}

/** 转时间日期 到天  yyyy-MM-dd HH:mm:ss*/
- (NSDate *)yh_dateToSecond{
    return [self yh_dateByFormate:nil];
}
/** 转时间日期 到天  yyyy-MM-dd*/
- (NSDate *)yh_dateToDay{
    return [self yh_dateByFormate:@"yyyy-MM-dd"];
}
/** 转时间日期 到天  yyyy-MM*/
- (NSDate *)yh_dateToMonth{
    return [self yh_dateByFormate:@"yyyy-MM"];
}

-(BOOL)yh_containStr:(NSString *)str{
    if(!str){
        return NO;
    }
    NSRange range = [self rangeOfString:str];
    //有包含
    if(range.location != NSNotFound ){
        return YES;
    }
    return NO;
}

- (BOOL)yh_isPureInt{
    NSScanner* scan = [NSScanner scannerWithString:self];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

- (BOOL)yh_isURL{
    NSString * regex = @"[a-zA-z]+://.*";

    NSPredicate * pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

    return [pre evaluateWithObject:self];
}

- (BOOL)yh_isIP{
    NSString * regex = @"(\\d*\\.){3}\\d*";

    NSPredicate * pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

    return [pre evaluateWithObject:self];
}

#pragma mark - 中英文输入限制

- (NSInteger)yh_stringLenthOfBytes{
    NSInteger length = 0;
    for (int i = 0; i< [self length]; i++) {
        //截取字符串中的每一个字符
        NSString *string = [self substringWithRange:NSMakeRange(i, 1)];
        if ([self validateChineseChar:string]) {
            //NSLog(@" s 打印信息:%@",s);
            length += 2;
        }else{
            length += 1;
        }
        //NSLog(@" 打印信息:%@  %ld",s,(long)length);
    }
    return length;
}

- (NSString *)yh_subBytesOfstringToIndex:(NSInteger)index{
    NSInteger length = 0;
    NSInteger chineseNum = 0;
    NSInteger zifuNum = 0;
    
    for (int i = 0; i< [self length]; i++) {
        //截取字符串中的每一个字符
        NSString *string = [self substringWithRange:NSMakeRange(i, 1)];
        if ([self validateChineseChar:string]){
            if (length + 2 > index){
                return [self substringToIndex:chineseNum + zifuNum];
            }
            
            length += 2;
            chineseNum += 1;
        }else{
            if (length + 1 > index){
                return [self substringToIndex:chineseNum + zifuNum];
            }
            length += 1;
            
            zifuNum += 1;
        }
    }
    return self;
}

//检测中文或者中文符号
- (BOOL)validateChineseChar:(NSString *)string{
    NSString *nameRegEx = @"[\\u0391-\\uFFE5]";
    if (![string isMatchesRegularExp:nameRegEx]) {
        return NO;
    }
    return YES;
}

//检测中文
- (BOOL)validateChinese:(NSString *)string{
    NSString *nameRegEx = @"[\u4e00-\u9fa5]";
    if (![string isMatchesRegularExp:nameRegEx]) {
        return NO;
    }
    return YES;
}

- (BOOL)isMatchesRegularExp:(NSString *)regex {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:self];
}

/// 数字键盘输入
- (NSString *)yh_decimalInput{
    NSMutableCharacterSet * charSet = [NSMutableCharacterSet decimalDigitCharacterSet];
    [charSet addCharactersInString:@"."];
    return [self yh_inputCharIsMemberInSet:charSet];
}

- (NSString *)yh_decimalNegativeInput{
    NSMutableCharacterSet * charSet = [NSMutableCharacterSet decimalDigitCharacterSet];
    [charSet addCharactersInString:@"."];
    [charSet addCharactersInString:@"-"];
    return [self yh_inputCharIsMemberInSet:charSet];
}

- (NSString *)yh_inputCharIsMemberInSet:(NSMutableCharacterSet *)charSet{
    
    NSString * value = self;
    
    if(value.length==0){
        return value;
    }

    if(![charSet characterIsMember:[value characterAtIndex:value.length-1]]){
        return [value substringToIndex:value.length-1];
    }
    
    if(value>0){
        NSString * lastChar = [value substringFromIndex:value.length - 1];
        NSString * firstChar = [value substringToIndex:1];
        if([lastChar isEqualToString:@"."]){
            if(value.length==1){
                value = @"0.";
            }else{
                NSRange pointRangePro = [value rangeOfString:@"."];
                NSRange pointRangeBack = [value rangeOfString:@"." options:(NSBackwardsSearch)];
                if(pointRangePro.location != pointRangeBack.location){
                    value = [value substringToIndex:value.length - 1];
                }
            }
        }
        if([firstChar isEqualToString:@"0"] &&
           value.length==2){
            if(![lastChar isEqualToString:@"."]){
                value = [value substringFromIndex:1];
            }
        }
//        if([lastChar isEqualToString:@"-"]){
//            if([firstChar ])
//        }
    }
    if([value containsString:@"."]){
        NSArray * listPoint = [value componentsSeparatedByString:@"."];
        NSString * pointStr = listPoint.lastObject;
        if(pointStr.length > 6){
            value = [value substringToIndex:value.length - 1];
        }
    }
    return value;
}

-(NSString *)yh_phoneSecret{
    if(self.length > 8){
        return [self stringByReplacingCharactersInRange:NSMakeRange(self.length-8, 4) withString:@"****"];
    }
    return self;
}

- (NSDictionary *)yh_getURLParam{
    
    if (self.length && [self rangeOfString:@"?"].length == 1) {
        NSArray *array = [self componentsSeparatedByString:@"?"];
        if (array && array.count == 2) {
            NSString *paramsStr = array[1];
            if (paramsStr.length) {
                NSMutableDictionary *paramsDict = [NSMutableDictionary dictionary];
                NSArray *paramArray = [paramsStr componentsSeparatedByString:@"&"];
                for (NSString *param in paramArray) {
                    if (param && param.length) {
                        NSArray *parArr = [param componentsSeparatedByString:@"="];
                        if (parArr.count == 2) {
                            [paramsDict setObject:parArr[1] forKey:parArr[0]];
                        }
                    }
                }
                return paramsDict;
            }else{
                return nil;
            }
        }else{
            return nil;
        }
    }else{
        return nil;
    }
}

/// 复制到粘贴板
- (void)yh_copy{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = self;
    if (@available(iOS 10.0, *)) {
        UIImpactFeedbackGenerator*impactLight = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleHeavy];
        [impactLight impactOccurred];
    } else {
        // Fallback on earlier versions
    }
    YHHUDMsg(@"复制成功");
//    [YHHUD showWithText:LS(@"复制成功")];
}

+ (BOOL)isChinese:(NSString *)text
{
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:text];
}

- (NSString *)yh_filterPhtonNumber{
    NSString * displayName = self;
    if (displayName.length > 10) {
        if ([displayName doubleValue] > 10000000000) {
            return [[self substringToIndex:7] stringByAppendingString:@"..."];
        }
        NSError * error;
        NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:@"\\W" options:0 error:&error];
        if (!error) {
            displayName = [displayName stringByReplacingOccurrencesOfString:@"_" withString:@""];
            displayName = [displayName stringByReplacingOccurrencesOfString:@" " withString:@""];
            NSArray <NSTextCheckingResult *>* expression = [regular matchesInString:displayName options:0 range:NSMakeRange(0, displayName.length)];
            NSMutableSet * replacString = [NSMutableSet set];
            for (NSTextCheckingResult *result in expression) {
               
                [replacString addObject:[displayName substringWithRange:result.range]];
            }
            for (NSString * resultStr in replacString) {
                displayName = [displayName stringByReplacingOccurrencesOfString:resultStr withString:@""];
            }
            displayName = [displayName stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
        }
        if ([displayName doubleValue] >= 10000000000) {
            return [[self substringToIndex:10] stringByAppendingString:@"..."];
        }
    }
    return self;
}
- (BOOL)isPhoneNum
{
    NSString *MOBILE = @"^1(3[0-9]|4[579]|5[0-35-9]|6[6]|7[0-35-9]|8[0-9]|9[89])\\d{8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    return [regextestmobile evaluateWithObject:self];
}




@end
